<template>
  <el-form ref="ruleFormRef" :model="skuInfo" :rules="skuRules">
    <el-form-item label="SPU名称" prop="skuName">
      <span>{{ props.currentSpuInfo.spuName }}</span>
    </el-form-item>
    <el-form-item label="SKU名称" prop="skuName">
      <el-input v-model="skuInfo.skuName" placeholder="SKU名称"></el-input>
    </el-form-item>
    <el-form-item label="价格（元）" prop="price">
      <el-input-number
        v-model="skuInfo.price"
        :min="1"
        :max="10"
        @change="handleChange"
      ></el-input-number>
    </el-form-item>
    <el-form-item label="重量（千克）" prop="weight">
      <el-input-number
        v-model="skuInfo.weight"
        :min="1"
        :max="10"
        @change="handleChange"
      ></el-input-number>
    </el-form-item>
    <el-form-item label="SKU描述" prop="skuDesc">
      <el-input
        type="textarea"
        placeholder="sku描述"
        v-model="skuInfo.skuDesc"
      ></el-input>
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row :gutter="10">
        <el-col
          :xs="24"
          :sm="12"
          :md="8"
          :lg="8"
          :xl="8"
          v-for="(attr, index) in attrList"
          :key="attr.id"
        >
          <el-select
            placeholder="请选择"
            v-model="skuInfo.skuAttrValueList[index]"
            @click="clearAttrRules"
          >
            <el-option
              v-for="attrValue in attr.attrValueList"
              :key="attrValue.id"
              :label="attrValue.valueName"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="销售属性" prop="saleAttrName">
      <el-form-item
        v-for="(saleAttr, index) in spuSaleAttrList"
        :key="saleAttr.id"
        :label="saleAttr.saleAttrName"
      >
        <el-select
          placeholder="请选择"
          v-model="skuInfo.skuSaleAttrValueList[index]"
          @change="clearSaleAttrRules"
        >
          <el-option
            v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
            :label="saleAttrValue.saleAttrValueName"
            :key="saleAttrValue.id"
            :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
          />
        </el-select>
      </el-form-item>
    </el-form-item>
    <el-form-item label="图片列表" prop="skuImageList">
      <el-table :data="spuImageList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="60px"></el-table-column>
        <el-table-column label="图片">
          <template v-slot="{ row }">
            <el-image
              style="width: 100px; height: 100px"
              :src="row.imgUrl"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              v-if="row.isDefault === '0'"
              type="primary"
              size="small"
              @click="setDefault(row)"
              >设为默认项</el-button
            >
            <el-button v-else type="success" size="small" disabled
              >默认项</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >保存</el-button
      >
      <el-button @click="emits('changeScene', 1)">取消</el-button>
    </el-form-item>
  </el-form>
</template>


<script lang="ts">
import { useCategorySelectorInfoStore } from "@/stores/categorySelector";
import { onMounted, reactive, ref } from "@vue/runtime-core";
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from "@/api/product/spu";
import { reqSaveSkuInfo } from "@/api/product/sku";
import { reqGetAttrListData } from "@/api/product/attr";
export default {
  name: "SkuForm",
};
</script>
<script lang="ts" setup>
import type { FormInstance, FormRules } from "element-plus";
const ruleFormRef = ref<FormInstance>();
const props = defineProps(["currentSpuInfo"]);
const emits = defineEmits(["changeScene"]);
const handleChange = (value: number) => {
  console.log(value);
};
// 定义三个变量来存储请求回来的数据
const spuImageList = ref([]);
const spuSaleAttrList = ref([]);
const attrList = ref([]);
// 自定义图片的校验规则
const validateSkuImageList = (rule: any, value: any, callback: any) => {
  if (value.length < 3) return callback(new Error("图片至少要三张"));
  const flag = value.some((item) => item.isDefault === "1");
  if (!flag)
    return callback(new Error("选择的图片中不包含默认项,请添加默认项"));
  callback();
};

const skuRules = reactive<FormRules>({
  skuName: [
    { required: true, message: "请输入sku名称", trigger: "blur" },
    { min: 2, max: 10, message: "sku名称长度在2--10之间", trigger: "blur" },
  ],
  skuDesc: [{ required: true, message: "请输入sku描述", trigger: "blur" }],
  price: [
    {
      type: "number",
      required: true,
      message: "价格不能为空",
      trigger: "blur",
    },
  ],
  weight: [{ required: true, message: "重量不能为空", trigger: "blur" }],
  skuImageList: [{ validator: validateSkuImageList, trigger: "blur" }],
  skuAttrValueList: [
    {
      type: "array",
      required: true,
      message: "请至少选择一项平台属性",
      trigger: "blur",
    },
  ],
  skuSaleAttrValueList: [
    {
      type: "array",
      required: true,
      message: "请至少选择一项销售属性",
      trigger: "blur",
    },
  ],
});


const skuInfo = reactive({
  // sku名称
  skuName: "",
  // sku描述
  skuDesc: "",
  // 重量
  weight: "1",
  // 价格
  price: 3,
  // 是否上架
  // isSale:0,
  // 三级分类id
  category3Id: 0,
  // 默认图片的链接地址
  skuDefaultImg: "",
  // 选择的图片列表
  skuImageList: [],
  // 平台属性列表
  skuAttrValueList: [],
  // 销售属性列表
  skuSaleAttrValueList: [],
});

const categoryStore = useCategorySelectorInfoStore();
onMounted(async () => {
  // 拿到当前的ID父组件传来的ID
  const id = props.currentSpuInfo.id;
  console.log(id);
  const [responseSpuImageList, responseSpuSaleAttrList, responseAttrList] =
    await Promise.allSettled([
      reqGetSpuImageList(id),
      reqGetSpuSaleAttrList(id),
      reqGetAttrListData({
        category1Id: categoryStore.category1Id,
        category2Id: categoryStore.category2Id,
        category3Id: categoryStore.category3Id,
      }),
    ]);
  console.log(responseSpuImageList, responseSpuSaleAttrList, responseAttrList);
  if (responseSpuImageList.status === "fulfilled") {
    spuImageList.value = responseSpuImageList.value.map((item) => {
      return {
        ...item,
        isDefault: "0", // 额外再次添加一个属性，用于区分是否默认项
      };
    });
  }
  if (responseSpuSaleAttrList.status === "fulfilled") {
    spuSaleAttrList.value = responseSpuSaleAttrList.value;
  }
  if (responseAttrList.status === "fulfilled") {
    attrList.value = responseAttrList.value;
  }
});

// 1. 页面挂载完毕 就要发送请求 获取页面中需要展示的三种数据
// 三级导航下的平台属性  spu相关的销售属性  spu相关的图片列表

// 获取图片列表
const handleSelectionChange = (val) => {
  skuInfo.skuImageList = val;
};
// 清除图片校验属性
const setDefault = (row) => {
  spuImageList.value.forEach((item) => (item.isDefault = "0"));
  row.isDefault = "1";
  // 收集默认的图片地址
  skuInfo.skuDefaultImg = row.imgUrl;
  // 清除图片的校验
  const imgArr = skuInfo.skuImageList;
  if (
    imgArr.length >= 3 &&
    imgArr.some((item) => {
      item.isDefault === "1";
    })
  ) {
    ruleFormRef.value?.clearValidate(["skuImageList"]);
  }
};

// 清除平台属性
const clearAttrRules = () => {
  const length = skuInfo.skuAttrValueList.filter(Boolean).length;
  if (length >= 3) {
    ruleFormRef.value?.clearValidate(["skuAttrValueList"]);
  }
};

// 清除销售属性校验
const clearSaleAttrRules = () => {
  // const length = skuInfo.skuSaleAttrValueList
  ruleFormRef.value?.clearValidate(["skuSaleAttrValueList"]);
};

// 将数据格式化，在发送请求时使用
const formatData = () => {
  skuInfo.skuAttrValueList = skuInfo.skuAttrValueList
    .filter(Boolean)
    .map((item: string) => {
      const [attrId, attrName, valueId, valueName] = item.split(":");
      return {
        attrId,
        attrName,
        valueId,
        valueName,
      };
    });
  skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList
    .filter(Boolean)
    .map((item: string) => {
      const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] =
        item.split(":");
      return { saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName };
    });
  skuInfo.spuId = props.currentSpuInfo.id;
  skuInfo.category3Id = props.currentSpuInfo.category3Id;
};
// 点击校验并提交数据发送请求
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // console.log("submit!");
      formatData();
      console.log(skuInfo);
      await reqSaveSkuInfo(skuInfo);
      emits("changeScene", 1);
    } else {
      console.log("error submit!", fields);
    }
  });
};
</script>

<style></style>
